package uk.co.q3c.deplan.server.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionUtils {
	/**
	 * Returns the value of the supplied field, but does so without setting the
	 * field as accessible. Instead it uses get methods constructed from the
	 * field name.
	 * 
	 * NOT TESTED
	 * 
	 * @param target
	 * @param field
	 * @param isBooleanField
	 * @return
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static Object getFieldValue(Object target, Field field, boolean isBooleanField) throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		String propertyName = field.getName();
		String prop = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
		Method method = null;
		Class<?>[] types = new Class[] {};
		if (isBooleanField) {
			try {
				String methodName = "is" + prop;
				method = target.getClass().getMethod(methodName, types);
			} catch (NoSuchMethodException e) {
				String methodName = "has" + prop;
				method = target.getClass().getMethod(methodName, types);

			}

		} else {
			try {
				String methodName = "get" + prop;
				method = target.getClass().getMethod(methodName, types);
			} catch (NoSuchMethodException e) {
				String methodName = propertyName;
				method = target.getClass().getMethod(methodName, types);

			}

		}
		return method.invoke(target, new Object[0]);
	}
}
